<template>
  <div class="mass-content-editor">
    <!-- 操作按钮区和标签选项在同一行 -->
    <div class="button-and-tag-row">
      <!-- 操作按钮区 -->
      <div class="button-group">
        <template v-for="btn in displayButtons" :key="btn.btnName">
          <!-- 图片上传特殊处理 -->
          <ElUpload
            v-if="
              btn.massSendTaskContentType ===
              MassSendTaskContentType.MassSendTaskContentTypeImage
            "
            class="upload-button"
            action=""
            accept="image/*"
            :before-upload="handleImageUpload"
            :show-file-list="false"
          >
            <ElButton :icon="btn.icon" plain>
              {{ tr(btn.btnName) }}
            </ElButton>
          </ElUpload>

          <!-- 素材库按钮特殊处理 -->
          <ElButton
            v-else-if="
              btn.massSendTaskContentType ===
              MassSendTaskContentType.MassSendTaskContentTypeUnknown
            "
            :icon="btn.icon"
            plain
            @click="handleMaterialLibrary"
          >
            {{ tr(btn.btnName) }}
          </ElButton>

          <!-- 其他按钮 -->
          <ElButton v-else :icon="btn.icon" plain @click="addContent(btn)">
            {{ tr(btn.btnName) }}
          </ElButton>
        </template>
      </div>

      <!-- 外部已提供是否使用表情选项（UseEmojiOption）；此处不再内置 -->
    </div>

    <!-- 内容表格 -->
    <div class="content-table">
      <ElTable
        :data="contentList"
        border
        :height="tableHeight"
        style="width: 100%"
      >
        <!-- 类型列 -->
        <ElTableColumn :label="tr('common.type')" width="100" align="center">
          <template #default="{ row }">
            {{ row && row.btnName ? tr(row.btnName) : "" }}
          </template>
        </ElTableColumn>

        <!-- 内容列 -->
        <ElTableColumn :label="tr('common.content')" align="center">
          <template #default="{ row }">
            <!-- 文本类型：显示输入框 -->
            <ElInput
              v-if="
                row &&
                row.massSendTaskContentType ===
                  MassSendTaskContentType.MassSendTaskContentTypeText
              "
              v-model="row.taskContent"
              type="textarea"
              autosize
              :placeholder="tr('session.enterContent')"
            />

            <!-- 通话类型：显示图标 -->
            <span v-else-if="row && isCallType(row.massSendTaskContentType)">
              <ElIcon :size="24">
                <component :is="row.icon" />
              </ElIcon>
            </span>

            <!-- 其他类型：使用 MessageDisplay 预览 -->
            <div v-else-if="row && showMessageDisplay">
              <slot name="content-preview" :item="toMessageDisplayItem(row)">
                <!-- 默认显示内容文本 -->
                <div class="content-preview">
                  <span v-if="row.taskContentUrl">{{
                    row.taskContentUrl
                  }}</span>
                  <span v-else>{{ row.taskContent }}</span>
                </div>
              </slot>
            </div>

            <!-- 如果不需要预览，显示简单文本 -->
            <div v-else class="content-preview">
              <span v-if="row && row.taskContentUrl">{{
                row.taskContentUrl
              }}</span>
              <span v-else>{{ row ? row.taskContent : "" }}</span>
            </div>
          </template>
        </ElTableColumn>

        <!-- 操作列 -->
        <ElTableColumn
          fixed="right"
          :label="tr('common.handle')"
          width="180"
          align="center"
        >
          <template #default="{ $index }">
            <div
              style="
                display: flex;
                gap: 4px;
                justify-content: center;
                flex-wrap: wrap;
              "
            >
              <!-- 上移 -->
              <ElButton
                v-if="
                  contentList.length > 1 &&
                  typeof $index === 'number' &&
                  $index !== 0
                "
                link
                size="small"
                @click="moveContent($index, -1)"
              >
                {{ tr("mass.moveUp") }}
              </ElButton>

              <!-- 下移 -->
              <ElButton
                v-if="
                  contentList.length > 1 &&
                  typeof $index === 'number' &&
                  $index !== contentList.length - 1
                "
                link
                size="small"
                @click="moveContent($index, 1)"
              >
                {{ tr("mass.moveDown") }}
              </ElButton>

              <!-- 删除 -->
              <ElButton
                link
                size="small"
                @click="typeof $index === 'number' && removeContent($index)"
              >
                {{ tr("common.delete") }}
              </ElButton>
            </div>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from "vue";
// Explicitly import Element Plus components to work in packaged builds
import { ElUpload, ElButton, ElTable, ElTableColumn, ElInput, ElIcon } from "element-plus";
import {
  MassSendTaskContentType,
  getMessageTypeFromMassSendType,
  DEFAULT_BUTTONS,
  type ButtonInfo,
  type ContentItem,
  type MessageDisplayItem,
} from "./types";

/**
 * Props
 */
const props = withDefaults(
  defineProps<{
    /** 内容列表（v-model） */
    modelValue: ContentItem[];
    /** 显示的按钮配置 */
    buttons?: ButtonInfo[];
    /** 表格高度 */
    tableHeight?: number | string;
    /** 翻译函数 */
    t?: (key: string) => string;
    /** 上传处理函数 */
    uploadHandler?: (file: File) => Promise<{ key: string; url: string }>;
    /** 是否显示内容预览（需要 MessageDisplay 组件支持） */
    showMessageDisplay?: boolean;
  }>(),
  {
    modelValue: () => [],
    buttons: () => DEFAULT_BUTTONS,
    tableHeight: 250,
    showMessageDisplay: false,
  }
);

/**
 * Emits
 */
const emit = defineEmits<{
  (e: "update:modelValue", value: ContentItem[]): void;
  (e: "openMaterialLibrary"): void;
}>();

/**
 * 内容列表
 */
const contentList = ref<ContentItem[]>([...props.modelValue]);


/**
 * 监听外部变化
 */
watch(
  () => props.modelValue,
  (newVal) => {
    console.log(
      "MassContentEditor: props.modelValue changed =",
      JSON.stringify(newVal)
    );
    console.log(
      "MassContentEditor: contentList.value before =",
      JSON.stringify(contentList.value)
    );
    if (JSON.stringify(newVal) !== JSON.stringify(contentList.value)) {
      contentList.value = [...newVal];
      console.log(
        "MassContentEditor: contentList updated =",
        JSON.stringify(contentList.value)
      );
    } else {
      console.log("MassContentEditor: contentList unchanged (same content)");
    }
  },
  { deep: true }
);

/**
 * 监听内部变化并同步到外部
 */
watch(
  contentList,
  (newVal) => {
    if (JSON.stringify(newVal) !== JSON.stringify(props.modelValue)) {
      emit("update:modelValue", newVal);
    }
  },
  { deep: true }
);

// 是否使用表情的选项由外部独立组件提供，此处不再维护

/**
 * 显示的按钮列表
 */
const displayButtons = computed(() => props.buttons || DEFAULT_BUTTONS);

/**
 * 翻译函数
 */
const tr = (key: string): string => {
  return props.t ? props.t(key) : key;
};

/**
 * 判断是否为通话类型
 */
const isCallType = (type: MassSendTaskContentType): boolean => {
  return (
    type === MassSendTaskContentType.MassSendTaskContentTypeVoiceCall ||
    type === MassSendTaskContentType.MassSendTaskContentTypeVideoCall
  );
};

/**
 * 转换为 MessageDisplay 需要的格式
 */
const toMessageDisplayItem = (item: ContentItem): MessageDisplayItem => {
  return {
    messageType: getMessageTypeFromMassSendType(item.massSendTaskContentType),
    messageContent: item.taskContent,
    messageContentUrl: item.taskContentUrl,
  };
};

/**
 * 添加内容
 */
const addContent = (btn: ButtonInfo) => {
  const newItem: ContentItem = {
    massSendTaskContentType: btn.massSendTaskContentType,
    btnName: btn.btnName,
    icon: btn.icon,
    taskContent: isCallType(btn.massSendTaskContentType) ? "30" : "",
    taskContentUrl: "",
  };
  contentList.value.push(newItem);
};

/**
 * 处理图片上传
 */
const handleImageUpload = async (file: File) => {
  if (!props.uploadHandler) {
    console.error("uploadHandler is not provided");
    return false;
  }

  try {
    const { key, url } = await props.uploadHandler(file);
    const imageBtn = displayButtons.value.find(
      (btn) =>
        btn.massSendTaskContentType ===
        MassSendTaskContentType.MassSendTaskContentTypeImage
    );

    if (imageBtn) {
      contentList.value.push({
        massSendTaskContentType:
          MassSendTaskContentType.MassSendTaskContentTypeImage,
        btnName: imageBtn.btnName,
        icon: imageBtn.icon,
        taskContent: key,
        taskContentUrl: url,
      });
    }
  } catch (error) {
    console.error("Upload failed:", error);
  }

  return false; // 阻止默认上传行为
};

/**
 * 移动内容
 */
const moveContent = (index: number, direction: number) => {
  const targetIndex = index + direction;
  if (targetIndex < 0 || targetIndex >= contentList.value.length) {
    return;
  }

  const temp = contentList.value[index];
  contentList.value[index] = contentList.value[targetIndex];
  contentList.value[targetIndex] = temp;
};

/**
 * 删除内容
 */
const removeContent = (index: number) => {
  contentList.value.splice(index, 1);
};

/**
 * 打开素材库
 */
const handleMaterialLibrary = () => {
  emit("openMaterialLibrary");
};
</script>

<style scoped lang="scss">
.mass-content-editor {
  width: 100%;

  .button-and-tag-row {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    flex-wrap: nowrap;
    overflow-x: auto;
  }

  .button-group {
    display: inline-flex;
    flex-wrap: nowrap;
    gap: 8px;
    align-items: center;
    flex-shrink: 1;

    .upload-button {
      :deep(.el-upload) {
        display: inline-block;
      }
    }
  }

  .use-tag-option {
    display: inline-flex;
    align-items: center;
    white-space: nowrap;
    padding: 0 12px;
    height: 32px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #fff;
    flex-shrink: 0;
    margin-left: auto;

    .option-label {
      font-size: 14px;
      font-weight: normal;
      color: #606266;
      margin-right: 8px;
    }

    :deep(.el-radio-group) {
      display: flex;
      align-items: center;
    }

    :deep(.el-radio) {
      margin-right: 12px;
      height: auto;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .content-table {
    width: 100%;

    .content-preview {
      padding: 8px;
      text-align: left;
      word-break: break-all;
      color: #606266;
      font-size: 14px;
    }
  }
}
</style>
